package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.CarlaClassicVo;
import com.jdy.haoduoai.model.LeHotRecomStory;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ImageLoader;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoai.R;

public class StoryDubPlayActivity extends BaseActivity implements
    OnClickListener, Callback {

  @SuppressWarnings("unused")
  private static final String TAG = StoryDubPlayActivity.class.getSimpleName();

  private static final String RECORD_PREFIX = "record_";

  static final String EXTENSION = ".mp3";

  private Button py_3;
  @InjectView(id = R.id.custom_channel)
  private LinearLayout custom_channel;
  @InjectView(id = R.id.dub_play, click = true)
  private Button dub_play;
  @InjectView(id = R.id.back, click = true)
  private ImageButton back;

  ImageView dub_img;
  private ImageLoader mImageLoader;
  String pic, name, share_data, audioStreamingURL;
  String videoStreamingURL;
  int id;
  // private Animation pressedAnimation;
  //
  // private int mWidth;
  //
  // private int mHeight;

  private RelativeLayout mRootLayout;

  private MediaPlayer audioMediaPlayer, videoMediaPlayer;

  private Button mPlayImageBtn;

  SurfaceView surfaceView;

  SurfaceHolder surfaceHolder;

  private int mPlayedTime;

  SeekBar pBar;

  private TextView start, end;

  int reslen;

  private boolean mIsInitialized = false;

  private boolean mIsFirstTime = true;

  private boolean mIsPlaying = false;

  private RelativeLayout mVideoLayout;
  private int mAudioPosition;
  private int mVideoPosition;

  private WakeLock mWakeLock;

  @SuppressWarnings("unused")
  private int banner_id, entity_id;
  @SuppressWarnings("unused")
  private String mix_audiopath, mix_videopath, mp3PathPost;

  private boolean mIsPause = false;
  private LeUser mLeUser;
  private ArrayList<LeHotRecomStory> mRecommendStroyList = null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.record_finish);
    hideTitleView();
    setTitle(getIntent().getStringExtra("name"));
    mWakeLock = Tools.getWakeLock(this, "preview clock");
    initView();
    setVideoHeight();

    loadRecommendStory();

  }

  private void setVideoHeight() {
    DisplayMetrics metrics = getResources().getDisplayMetrics();

    int w = metrics.widthPixels;

    int h = w * 3 / 4;

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, h);

    mVideoLayout.setLayoutParams(params);

    RelativeLayout.LayoutParams seekBarParams = (RelativeLayout.LayoutParams) pBar
        .getLayoutParams();

    seekBarParams.topMargin = h - Tools.getPixelByDip(this, 10);

    pBar.setLayoutParams(seekBarParams);
  }

  private void loadRecommendStory() {

    if (mLeUser == null) {
      mLeUser = Tools.restoreLeUser();
    }

    new CustomAsyncTask(this, new IAsyncTask() {
      @SuppressWarnings("unchecked")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          if (mRecommendStroyList != null) {
            mRecommendStroyList.clear();
          }

          if (Tools.isNotEmpty(result.data)) {
            mRecommendStroyList = (ArrayList<LeHotRecomStory>) JsonSerializer
                .getInstance().deserialize(result.data, ArrayList.class,
                    LeHotRecomStory.class);
            setRecommendStoryView(mRecommendStroyList);
          }
        }

      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        return HttpUtils.startRequest(HttpUtils.HOST_API
            + "/api/2.0/catalog/story/recommand", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private CarlaClassicVo convert2CarlaClassicVo(LeHotRecomStory recommendStroy) {
    if (recommendStroy == null)
      return null;
    LeHotRecomStory lhr = recommendStroy;
    CarlaClassicVo ccv = new CarlaClassicVo();
    ccv.id = lhr.id; // );
    ccv.category_id = lhr.category_id; // );
    ccv.catalog = lhr.catalog; // );
    ccv.name = lhr.name; // );
    ccv.cover = lhr.cover;// );
    ccv.url = lhr.url;// );
    ccv.enabled = lhr.enabled; // );
    ccv.sort = lhr.sort; // );
    ccv.length = lhr.length; // );
    ccv.agefrom = 0; // );
    ccv.ageto = 0;
    ccv.lines = lhr.lines; // );
    ccv.created_at = lhr.created_at; // );
    ccv.updated_at = lhr.updated_at; // );
    ccv.deleted_at = lhr.deleted_at; // );
    ccv.followers = lhr.followers;// );
    ccv.corner_icon = lhr.corner_icon; // );
    ccv.author = lhr.author; // );
    ccv.tags = lhr.tags; // );

    return ccv;
  }

  @SuppressLint("InflateParams")
  private void setRecommendStoryView(List<LeHotRecomStory> rList) {
    custom_channel.removeAllViews();
    int i = 0;
    int size = rList.size();
    for (; i < size; i++) {
      final LeHotRecomStory lhr = rList.get(i);
      View hChild = LayoutInflater.from(this).inflate(
          R.layout.horizontallist_item, null);
      final ImageView coverImg = (ImageView) hChild.findViewById(R.id.img);
      ImageView playStateImg = (ImageView) hChild
          .findViewById(R.id.play_state_img);
      playStateImg.setVisibility(View.GONE);
      coverImg.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
          Intent recode = new Intent();
          Bundle bundle = new Bundle();
          bundle.putSerializable("carlaclassic", convert2CarlaClassicVo(lhr));
          recode.putExtras(bundle);
          recode.setClass(StoryDubPlayActivity.this, RecordActivity2.class);
          startActivity(recode);
        }
      });
      coverImg.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

      TextView titleTv = (TextView) hChild.findViewById(R.id.tittle);

      titleTv.setText(lhr.name);

      if (Tools.isNotEmpty(lhr.cover))
        Picasso.with(this).load(lhr.cover)
            .placeholder(getResources().getDrawable(R.drawable.default_cover))
            .error(getResources().getDrawable(R.drawable.default_cover))
            .into(coverImg, new com.squareup.picasso.Callback() {

              @Override
              public void onSuccess() {
                // TODO Auto-generated method stub

              }

              @Override
              public void onError() {
                if (mImageLoader == null) {
                  mImageLoader = new ImageLoader(StoryDubPlayActivity.this);
                }
                mImageLoader.DisplayImage(lhr.cover, coverImg, false);

              }
            });

      LinearLayout.LayoutParams params_image = new LinearLayout.LayoutParams(
          LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

      params_image.setMargins(Tools.getPixelByDip(this, 5), 0,
          Tools.getPixelByDip(this, 5), 0);

      hChild.setLayoutParams(params_image);

      custom_channel.addView(hChild);
    }
  }

  private void initView() {

    mVideoLayout = (RelativeLayout) findViewById(R.id.video_layout);
    pBar = (SeekBar) findViewById(R.id.playbar);
    start = (TextView) findViewById(R.id.start);
    start.setText("0:00");
    end = (TextView) findViewById(R.id.end);

    mPlayImageBtn = (Button) findViewById(R.id.preview_play_btn);

    mRootLayout = (RelativeLayout) findViewById(R.id.story_dub_play_layout);
    mRootLayout.getViewTreeObserver().addOnGlobalLayoutListener(
        new OnGlobalLayoutListener() {

          @Override
          public void onGlobalLayout() {

            // mWidth = mRootLayout.getWidth();
            //
            // mHeight = mRootLayout.getHeight();
          }
        });

    // pressedAnimation = AnimationUtils.loadAnimation(this,
    // R.anim.anim_pressed);

    Intent it = getIntent();
    reslen = it.getIntExtra("reslen", 0);
    if (reslen > 0) {
      end.setText("/" + DateUtils.getTime(reslen));
      pBar.setMax(reslen);
    } else {
      end.setText("0:00");
    }
    id = it.getIntExtra("id", 0);

    mix_audiopath = it.getStringExtra("mix_audiopath");
    mix_videopath = it.getStringExtra("mix_videopath");

    mp3PathPost = it.getStringExtra("mp3PathPost");

    entity_id = it.getIntExtra("entity_id", -1);

    banner_id = it.getIntExtra("banner_id", -1);

    dub_img = (ImageView) findViewById(R.id.video_image);
    pic = it.getStringExtra("pic2");
    name = it.getStringExtra("name");
    audioStreamingURL = it.getStringExtra("voice");
    if (audioStreamingURL == null)
      audioStreamingURL = Environment.getExternalStorageDirectory()
          .getAbsolutePath()
          + "/haoduoai/"
          + RECORD_PREFIX
          + name
          + EXTENSION;

    videoStreamingURL = it.getStringExtra("video");
    if (videoStreamingURL == null) {
      videoStreamingURL = Environment.getExternalStorageDirectory()
          + "/haoduoai/" + name + ".mp4";
    }
    share_data = it.getStringExtra("share_data");
    mImageLoader = new ImageLoader(this);
    mImageLoader.DisplayImage(pic, dub_img, false);

    py_3 = (Button) findViewById(R.id.shares);
    py_3.setOnClickListener(this);
    py_3.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

    if (dub_play != null)
      dub_play.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

    mPlayImageBtn.setOnClickListener(this);
    mVideoLayout.setOnClickListener(this);

  }

  @Override
  public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putInt("audio_position", mAudioPosition);
    savedInstanceState.putInt("video_position", mVideoPosition);
  }

  @Override
  public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    mAudioPosition = savedInstanceState.getInt("audio_position");
    mVideoPosition = savedInstanceState.getInt("video_position");
  }

  @Override
  public void onResume() {
    super.onResume();
    if (surfaceView != null)
      surfaceView.setVisibility(View.VISIBLE);
    mIsPause = false;
    if (mWakeLock != null)
      mWakeLock.acquire();
  }

  @Override
  public void onPause() {
    super.onPause();
    if (surfaceView != null)
      surfaceView.setVisibility(View.GONE);
    mIsPause = true;
    if (mWakeLock != null) {
      mWakeLock.release();
    }
    if (audioMediaPlayer != null) {
      mAudioPosition = audioMediaPlayer.getCurrentPosition();
      audioMediaPlayer.stop();
      audioMediaPlayer.release();
      audioMediaPlayer = null;
    }
    if (videoMediaPlayer != null) {
      mVideoPosition = videoMediaPlayer.getCurrentPosition();
      videoMediaPlayer.stop();
      videoMediaPlayer.release();
      videoMediaPlayer = null;
    }
  }

  String mp4PathPost;

  private void submitDubStory() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        dismissLoading();
        if (result.isSuccess()) {
          // toastShow("上传成功");
          // finish();
        } else {
          dismissLoading();
          toastShow(result.data);
        }

        Intent intent;
        intent = new Intent(StoryDubPlayActivity.this, SharePopupWindow.class);
        intent.putExtra("pic", pic);
        intent.putExtra("name", name);
        intent.putExtra("id", id);
        intent.putExtra("share_data", share_data);
        startActivity(intent);
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        // param_.put("entity_id", entity_id);
        // param_.put("av", mp3PathPost);
        param_.put("merge_av", mp4PathPost);
        // param_.put("catalog", "story");
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.GET_DUBS_METHOD_GET, param_, HttpUtils.TAG_PUT_REQUEST);

      }
    }).execute("请检查网络连接!");
  }

  private void uploadVedioFile(final String filePath) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          mp4PathPost = result.data;
          submitDubStory();
        } else {
          dismissLoading();
          toastShow(result.data);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_MOBILE_I, lu.id);
        param_.put(HttpUtils.TAG_MODULE_I, "dub/story");
        return HttpUtils.startUploadRequest(HttpUtils.API_URL
            + HttpUtils.UPLOAD_BABY_AVATAR_POST, param_, "Filedata", filePath,
            HttpUtils.TAG_POST_REQUEST);

      }
    }).execute("请检查网络连接!");
  }

  private void mixAudioVedio() {
    final String pathBase = Environment.getExternalStorageDirectory()
        .getAbsolutePath() + "/" + getPackageName();

    File fMP4 = new File(pathBase + "/mixfinalvideo.mp4");
    if (fMP4.exists()) {
      fMP4.delete();
    }

    new Thread() {
      @Override
      public void run() {

        try {
          String audioEnglish = mix_audiopath;
          String video = mix_videopath;

//          Movie countVideo = MovieCreator.build(video);
//          Movie countAudioEnglish = MovieCreator.build(audioEnglish);
//
//          Track audioTrackEnglish = countAudioEnglish.getTracks().get(0);
//
//          if (countVideo.getTracks().size() <= 1) {
//            countVideo.addTrack(audioTrackEnglish);
//          } else {
//            countVideo.getTracks().add(1, audioTrackEnglish);
//          }
//
//          {
//            Container out = new DefaultMp4Builder().build(countVideo);
//            FileOutputStream fos = new FileOutputStream(new File(pathBase
//                + "/mixfinalvideo.mp4"));
//            out.writeContainer(fos.getChannel());
//            fos.close();
//          }

          // 1 step

      //    uploadVedioFile(pathBase + "/mixfinalvideo.mp4");

          uploadVedioFile(video);

        } catch (Exception e) {
          runOnUiThread(new Runnable() {
            @Override
            public void run() {
              dismissLoading();
            }
          });
        }

      };
    }.start();
  }

  @Override
  public void onClick(View v) {
    // Intent intent = new Intent();
    switch (v.getId()) {
    case R.id.back:
      finish();
      break;
    case R.id.dub_play:
      playvideo(id);
      break;

    case R.id.shares:
      showloading("");
      toastShow("请稍候");
      mixAudioVedio();
      break;
    case R.id.preview_play_btn:
      if (!mIsInitialized) {
        mIsInitialized = true;
        previewRecord(id, "init");
      } else {
        previewRecord(id, "continue");
      }
      break;
    case R.id.video_layout:
      if (mIsInitialized) {
        if (!isShowLoading()) {
          if (mIsPlaying) {
            previewRecord(id, "pause");
          } else {
            previewRecord(id, "continue");
          }
        }
      }
      break;
    default:
      break;
    }
  }

  private void previewRecord(int playId, String action) {
    if (action.equals("init") && Tools.isNotEmpty(audioStreamingURL)) {
      surfaceView = (SurfaceView) findViewById(R.id.preview_video);
      surfaceView.setVisibility(View.VISIBLE);
      surfaceHolder = surfaceView.getHolder();
      surfaceHolder.addCallback(this);
      surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    } else if (action.equals("continue")) {
      mPlayImageBtn.setVisibility(View.GONE);
      mIsPlaying = true;
      surfaceView.setAlpha(1.0f);
      if (audioMediaPlayer != null)
        audioMediaPlayer.start();
      if (videoMediaPlayer != null) {
        videoMediaPlayer.start();
      }

    } else if (action.equals("pause")) {
      mPlayImageBtn.setVisibility(View.VISIBLE);
      mIsPlaying = false;
      surfaceView.setAlpha(0.7f);
      if (audioMediaPlayer != null)
        audioMediaPlayer.pause();
      if (videoMediaPlayer != null) {
        videoMediaPlayer.pause();
      }
    }
  }

  private void playvideo(final int sid) {
    new CustomAsyncTask(StoryDubPlayActivity.this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          if (LeConfig.isDeviceConnect) {
            toastShow("已推送到设备播放!");
          } else {
            toastShow("未连接到设备，请检查设备联网情况！");
          }
        } else {
          LeConfig.isDeviceConnect = false;
          toastShow("设备不在线");
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        int uid = -1, volume = -1, minutes = -1;

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
        param_.put(HttpUtils.TAG_OPERATION_I, "dub");
       // param_.put("mode", "im");

        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }
        if (uid != -1) {
          param_.put(HttpUtils.TAG_UID_I, String.valueOf(uid));
        }
        if (volume != -1) {
          param_.put(HttpUtils.TAG_VOLUME, String.valueOf(volume));
        }
        if (minutes != -1) {
          param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(minutes));
        }
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        if (banner_id >= 0) {
          param_.put("reference", "banner");
          param_.put("banner_id", banner_id);
        } else {
          param_.put("reference", "push");
        }

        param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  @Override
  public void surfaceChanged(SurfaceHolder holder, int format, int width,
      int height) {

  }

  @Override
  public void surfaceCreated(SurfaceHolder holder) {

    new AsyncTask<Void, Void, Void>() {

      @Override
      protected void onPreExecute() {
        mPlayImageBtn.setVisibility(View.GONE);
        showloading("");
        if (videoMediaPlayer != null) {
          videoMediaPlayer.release();
          videoMediaPlayer = null;
        }
        if (audioMediaPlayer != null) {
          audioMediaPlayer.release();
          audioMediaPlayer = null;
        }
      }

      @Override
      protected Void doInBackground(Void... params) {

        try {
          videoMediaPlayer = new MediaPlayer();
          videoMediaPlayer.setDisplay(surfaceHolder);
          videoMediaPlayer.setDataSource(videoStreamingURL);
          videoMediaPlayer.prepare();
          // videoMediaPlayer.start();

          audioMediaPlayer = new MediaPlayer();
          audioMediaPlayer.setWakeMode(getApplicationContext(),
              PowerManager.PARTIAL_WAKE_LOCK);
          audioMediaPlayer.setDataSource(audioStreamingURL);
          audioMediaPlayer.prepare();
        } catch (Exception e) {
          e.printStackTrace();
        }
        return null;
      }

      @Override
      protected void onPostExecute(Void result) {
        dismissLoading();

        mIsPlaying = true;
        mPlayImageBtn.setVisibility(View.GONE);
        if (reslen > 0 && videoMediaPlayer != null) {
          int seconds = videoMediaPlayer.getDuration() / 1000;
          end.setText("/" + DateUtils.getTime(seconds));
          pBar.setMax(seconds);
        }

        if (videoMediaPlayer != null && audioMediaPlayer != null) {
          new Thread(new UIUpdateThread()).start();
          if (mIsFirstTime) {
            videoMediaPlayer.start();
            audioMediaPlayer.start();
            mIsFirstTime = false;
          } else {
            videoMediaPlayer.start();
            videoMediaPlayer.seekTo(mVideoPosition);
            audioMediaPlayer.start();
            audioMediaPlayer.seekTo(mAudioPosition);
            previewRecord(id, "pause");
          }
        }

        // if (videoMediaPlayer != null && audioMediaPlayer != null) {
        // new Thread(new UIUpdateThread()).start();
        //
        // videoMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
        //
        // @Override
        // public void onPrepared(MediaPlayer mp) {
        //
        //
        // if (mIsFirstTime) {
        // mp.start();
        // } else {
        // mp.start();
        // mp.seekTo(mVideoPosition);
        // }
        // }
        // });
        //
        // audioMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
        //
        // @Override
        // public void onPrepared(MediaPlayer mp) {
        //
        // if (mIsFirstTime) {
        // mp.start();
        // mIsFirstTime = false;
        // } else {
        // mp.start();
        // mp.seekTo(mAudioPosition);
        // previewRecord(id, "pause");
        // }
        // }
        // });
        // }
      }

    }.execute((Void[]) null);
  }

  private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      switch (msg.what) {
      case 5: {
        start.setText(DateUtils.getTime(mPlayedTime / 1000));
        pBar.setProgress(mPlayedTime / 1000);
        break;
      }
      default:
        break;
      }
    }
  };

  class UIUpdateThread implements Runnable {
    long time = 500; // 滚动速度

    @Override
    public void run() {
      while (videoMediaPlayer != null) {
        try {
          if (!mIsPause && videoMediaPlayer.isPlaying()) {
            mPlayedTime = videoMediaPlayer.getCurrentPosition();
            mHandler.sendEmptyMessage(5);
            Thread.sleep(time);
          }
        } catch (InterruptedException e) {
          videoMediaPlayer = null;
          e.printStackTrace();
        }
      }
    }
  }

  @Override
  public void surfaceDestroyed(SurfaceHolder holder) {

    if (videoMediaPlayer != null) {
      videoMediaPlayer.stop();
    }
    if (audioMediaPlayer != null) {
      audioMediaPlayer.stop();
    }
  }
}
